<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// ----- 数据状态 -----
const tasks = reactive<any[]>([])
const patrolDetails = reactive<any[]>([])
const patrols = reactive<any[]>([])
const photos = reactive<any[]>([])

// 筛选状态
const filterTaskName = ref('')
const filterType = ref('')
const filterArea = ref('')
const filterStatus = ref('')

const selectedTask = ref<any>(null)
const showDialog = ref(false)
const editingTask = ref<any>({})

const typeOptions = ['夜巡', '日巡', '例行']
const areaOptions = ['A区', '出入口', '停车场']

// 过滤任务列表
const filteredTasks = computed(() => {
  return tasks.filter(t => {
    return (!filterTaskName.value || t.taskName?.includes(filterTaskName.value))
        && (!filterType.value || t.patrolType === filterType.value)
        && (!filterArea.value || t.patrolArea === filterArea.value)
        && (!filterStatus.value || t.status === filterStatus.value)
  })
})

// 状态文本
function statusText(s: string) { return s === '0' ? '未开始' : s === '1' ? '进行中' : '已完成' }

// 通过ID查找巡逻详情
function detailById(id: number) {
  if (id === undefined || id === null) return {}
  return patrolDetails.find(d => d.id === id) || {}
}

// ---------------- API 调用 ----------------
async function fetchTasks() {
  try {
    const res = await fetch('http://localhost:9030/task/list')
    const data = await res.json()
    tasks.length = 0
    data.rows?.forEach((t: any) => tasks.push(t))
  } catch (e) { console.error(e); ElMessage.error('获取任务列表失败') }
}

async function fetchPatrolDetails() {
  try {
    const res = await fetch('http://localhost:9030/detail/list')
    const data = await res.json()
    patrolDetails.length = 0
    data.rows?.forEach((d: any) => patrolDetails.push(d))
  } catch (e) { console.error(e); ElMessage.error('获取巡逻详情失败') }
}

async function fetchPatrols() {
  try {
    const res = await fetch('http://localhost:9030/patroll/list')
    const data = await res.json()
    patrols.length = 0
    data.rows?.forEach((p: any) => patrols.push(p))
  } catch (e) { console.error(e); ElMessage.error('获取巡逻记录失败') }
}

async function fetchPhotos() {
  try {
    const res = await fetch('http://localhost:9030/photos/list')
    const data = await res.json()
    photos.length = 0
    if (data.rows && Array.isArray(data.rows)) {
      data.rows.forEach((p: any) => {
        photos.push({
          ...p,
          patrol_photo: p.patrolPhoto,
          buserId: p.buserId,
          pictureTime: p.pictureTime,
          longitude: isNaN(parseFloat(p.longitude)) ? parseFloat(p.dimension) || 0 : parseFloat(p.longitude),
          latitude: isNaN(parseFloat(p.latitude)) || parseFloat(p.latitude) === 0 ? parseFloat(p.dimension) || 0 : parseFloat(p.latitude),
        })
      })
    }
  } catch (e) { console.error(e); ElMessage.error('获取照片失败') }
}

// ---------------- 任务操作 ----------------
function selectTask(t: any) { selectedTask.value = t }

function openCreate() {
  editingTask.value = {
    taskName: '',
    patrolType: '',
    patrolArea: '',
    patrolRoute: '',
    patrolFrequency: '',
    startTime: '',
    endTime: '',
    status: '0'
  };
  showDialog.value = true
}

function openEdit(t: any) { editingTask.value = { ...t }; showDialog.value = true }

async function saveTask() {
  try {
    if (!editingTask.value) { ElMessage.error('没有可保存的任务数据'); return }

    const url = editingTask.value.id
        ? 'http://localhost:9030/task'
        : 'http://localhost:9030/task';
    const method = editingTask.value.id ? 'PUT' : 'POST';

    const response = await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(editingTask.value)
    });

    if (response.ok) {
      const result = await response.json();
      if (result.code === 200) {
        ElMessage.success(editingTask.value.id ? '任务更新成功' : '任务创建成功');
        showDialog.value = false;
        editingTask.value = {};
        await fetchTasks();
      } else { ElMessage.error(result.msg || '操作失败'); }
    } else { ElMessage.error('网络请求失败'); }
  } catch (error) { console.error(error); ElMessage.error('保存任务失败'); }
}

// ---------------- 地图逻辑 ----------------
let globalMap: any = null

function initMap() {
  if (globalMap) return;
  const mapContainer = document.getElementById('mapContainer');
  if (!mapContainer) return;

  const firstPhoto = photos[0];
  const defaultLng = firstPhoto?.longitude || 116.481488;
  const defaultLat = firstPhoto?.latitude || firstPhoto?.dimension || 39.996141;

  globalMap = new AMap.Map(mapContainer, { zoom: 17, center: [defaultLng, defaultLat] });
  globalMap.addControl(new AMap.Scale());
  globalMap.addControl(new AMap.ToolBar());

  const marker = new AMap.Marker({ position: [defaultLng, defaultLat], title: '巡逻点位' });
  globalMap.add(marker);
}

function loadAMapScript() {
  if ((window as any).AMap) { initMap(); return }
  ;(window as any)._AMapSecurityConfig = { securityJsCode: "3294aa3d3b2a482383e087452080b0d9" }
  const script = document.createElement('script');
  script.src = 'https://webapi.amap.com/maps?v=2.0&key=eec0d44028d6ba50a0506f86c9feeeea&plugin=AMap.Scale,AMap.ToolBar&callback=initAMap';
  script.onerror = () => { console.error('高德地图API加载失败'); };
  document.head.appendChild(script)
}
;(window as any).initAMap = () => { initMap() }

onMounted(() => {
  fetchTasks()
  fetchPatrolDetails()
  fetchPatrols()
  fetchPhotos()
  loadAMapScript()
})

function handleImageError(photo: any, event: Event) { console.error('图片加载失败:', photo, event) }
function handleImageLoad(photo: any, event: Event) { console.log('图片加载成功:', photo) }

function zoomToPatrolPoint(photo: any) {
  const longitude = photo.longitude;
  const latitude = photo.latitude;

  const position = (!longitude || !latitude || isNaN(longitude) || isNaN(latitude))
      ? [116.481488, 39.996141]
      : [longitude, latitude];

  if (!globalMap) return;
  if (window.patrolMarker) globalMap.remove(window.patrolMarker);

  window.patrolMarker = new AMap.Marker({
    position,
    title: `巡逻点位 - ${photo.buserId}`,
    label: { content: `员${photo.buserId}`, offset: new AMap.Pixel(0, -20) }
  });

  globalMap.add(window.patrolMarker);
  globalMap.setCenter(position);
  globalMap.setZoom(18);
}
</script>

<template>
  <div class="app-wrap">
    <el-row justify="space-between" align="middle" class="mb-3">
      <el-col><h2 style="margin:0 0 8px 0">安保巡逻管理控制台</h2></el-col>
      <el-col><el-button type="primary" @click="openCreate">新建任务</el-button></el-col>
    </el-row>

    <el-row :gutter="16">
      <!-- 左侧任务列表 -->
      <el-col :span="6">
        <el-card>
          <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
            <div style="font-weight:600">任务列表</div>
            <div class="muted" style="font-size:12px">{{ filteredTasks.length }} 项</div>
          </div>

          <el-input v-model="filterTaskName" placeholder="按任务名搜索" clearable size="small" class="mb-2"/>
          <el-select v-model="filterType" placeholder="巡逻类型" clearable size="small" class="mb-2">
            <el-option v-for="t in typeOptions" :key="t" :label="t" :value="t"/>
          </el-select>
          <el-select v-model="filterArea" placeholder="区域" clearable size="small" class="mb-2">
            <el-option v-for="a in areaOptions" :key="a" :label="a" :value="a"/>
          </el-select>
          <el-select v-model="filterStatus" placeholder="状态" clearable size="small">
            <el-option label="未开始" value="0"/>
            <el-option label="进行中" value="1"/>
            <el-option label="已完成" value="2"/>
          </el-select>

          <el-scrollbar style="max-height:520px; margin-top:8px">
            <el-row :gutter="8">
              <el-col :span="24" v-for="task in filteredTasks" :key="task.id">
                <el-card shadow="hover" class="task-card" @click="selectTask(task)">
                  <div style="display:flex;justify-content:space-between;align-items:center">
                    <div>
                      <div style="font-weight:600">{{ task.taskName }}</div>
                      <div class="muted" style="font-size:12px">{{ task.patrolType }} · {{ task.patrolArea }} · {{ task.patrolFrequency }}</div>
                      <div class="muted" style="font-size:12px">{{ task.startTime }} - {{ task.endTime }}</div>
                    </div>
                    <el-tag :type="task.status==='0'?'danger':task.status==='1'?'warning':'success'">{{ statusText(task.status) }}</el-tag>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧主区 -->
      <el-col :span="18">
        <el-card class="mb-3 map-card"><div id="mapContainer"></div></el-card>

        <el-row :gutter="12" class="mb-3">
          <el-col :span="12">
            <el-card>
              <div style="font-weight:600;margin-bottom:8px">巡逻记录</div>
              <el-table :data="patrols" height="240" border>
                <el-table-column prop="buserId" label="巡逻员ID" width="100"/>
                <el-table-column prop="buserPhone" label="手机" width="130"/>
                <el-table-column label="路线/明细" width="220">
                  <template #default="{row}">
                    <div>{{ detailById(row.patrolDetailId).patrolRoute || '-' }}</div>
                    <div class="muted" style="font-size:12px">{{ detailById(row.patrolDetailId).patrolArea || '' }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="patrolTime" label="打卡时间" width="180"/>
              </el-table>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card>
              <div style="font-weight:600;margin-bottom:8px">打卡照片</div>
              <el-scrollbar style="height:240px">
                <el-row :gutter="8">
                  <el-col v-for="ph in photos" :key="ph.id" :span="8">
                    <div class="photo-card">
                      <img :src="ph.patrol_photo" class="photo" @error="handleImageError(ph, $event)" @load="handleImageLoad(ph, $event)" @click="zoomToPatrolPoint(ph)"/>
                      <div style="font-size:12px;margin-top:4px;padding:4px 0;">员 {{ ph.buserId }} · <span class="muted">{{ ph.pictureTime }}</span></div>
                    </div>
                  </el-col>
                </el-row>
              </el-scrollbar>
            </el-card>
          </el-col>
        </el-row>

        <el-card>
          <div style="font-weight:600;margin-bottom:8px">任务详情</div>
          <div v-if="selectedTask">
            <el-row :gutter="12">
              <el-col :span="8"><div class="muted">任务名</div><div style="font-weight:600">{{ selectedTask.taskName }}</div></el-col>
              <el-col :span="8"><div class="muted">类型 / 区域</div><div style="font-weight:600">{{ selectedTask.patrolType }} · {{ selectedTask.patrolArea }}</div></el-col>
              <el-col :span="8"><div class="muted">频率</div><div style="font-weight:600">{{ selectedTask.patrolFrequency }}</div></el-col>
              <el-col :span="12" style="margin-top:12px"><div class="muted">路线</div><div style="font-weight:600">{{ selectedTask.patrolRoute }}</div></el-col>
              <el-col :span="12" style="margin-top:12px"><div class="muted">时间范围</div><div style="font-weight:600">{{ selectedTask.startTime }} — {{ selectedTask.endTime }}</div></el-col>
            </el-row>
          </div>
          <div v-else class="muted">请在左侧选择任务以查看详情</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新建/编辑任务弹窗 -->
    <el-dialog :title="editingTask?.id ? '编辑任务' : '新建任务'" v-model="showDialog" width="600px">
      <el-form :model="editingTask" label-width="90px">
        <el-form-item label="任务名称"><el-input v-model="editingTask.taskName"/></el-form-item>
        <el-form-item label="巡逻类型">
          <el-select v-model="editingTask.patrolType" placeholder="请选择">
            <el-option v-for="t in typeOptions" :key="t" :label="t" :value="t"/>
          </el-select>
        </el-form-item>
        <el-form-item label="区域">
          <el-select v-model="editingTask.patrolArea" placeholder="请选择">
            <el-option v-for="a in areaOptions" :key="a" :label="a" :value="a"/>
          </el-select>
        </el-form-item>
        <el-form-item label="路线"><el-input v-model="editingTask.patrolRoute"/></el-form-item>
        <el-form-item label="频率"><el-input v-model="editingTask.patrolFrequency"/></el-form-item>
        <el-form-item label="开始时间"><el-date-picker v-model="editingTask.startTime" type="datetime" style="width:100%"/></el-form-item>
        <el-form-item label="结束时间"><el-date-picker v-model="editingTask.endTime" type="datetime" style="width:100%"/></el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editingTask.status">
            <el-radio :label="'0'">未开始</el-radio>
            <el-radio :label="'1'">进行中</el-radio>
            <el-radio :label="'2'">已完成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" @click="saveTask">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.app-wrap { padding:16px }
.mb-2 { margin-bottom:8px }
.mb-3 { margin-bottom:12px }
.muted { color:#999 }
.map-card { height:280px }
#mapContainer { width:100%;height:260px }
.task-card { cursor:pointer; margin-bottom:8px }
.photo-card { text-align:center }
.photo { width:100%;height:80px;object-fit:cover;cursor:pointer }
</style>
